const app = getApp()
const host = 'https://plant.vistaagri.com/prod-api'

const timeout = 30000

const black = [

]

// 拦截
function intercept (res, fun, error) {
  console.log('res------------')
  console.log(res)
  if (typeof res.data == 'string') {
    res.data = JSON.parse(res.data)
  }

  // 改域名
  // gym(res.data)

  // 失败拦截
  if ( black.indexOf(res.data.code) > -1 ) {
    wx.showModal({
      title: '提示',
      content: res.data.msg,
      showCancel: false
    })
    if (error) {
      error(res.data)
    }
    return
  }
  

  if (res.data.code == 401) {
    wx.showModal({
      title: '提示',
      content: '当前账号未登录，请前往登陆',
      success (res) {
        if (res.confirm) {
          app.globalData.tabbarActive = 2
          wx.switchTab({
            url: '/pages/user/user'
          })
        }
      }
    })
    return
  }

  // 成功放行
  if (res.data.code == 200 || res.data.code == 0) {
    fun(res.data)
    return
  }
}


export const request = function (apiData, resolve, reject) {
  let url = apiData.url
  if (apiData.type == 'default' || !apiData.type) {
    wx.request({
      url,
      method: apiData.method || 'POST',
      header: {
        Authorization: app.globalData.accessToken ? 'Bearer ' + app.globalData.accessToken : '',
        'tenant-id': app.globalData.tenantId
      },
      data: apiData.data,
      timeout,
      success: function (res) {
        intercept(res, resolve, reject)
      },
      fail: function (err) {
        reject(err)
      }
    })

  } else if (apiData.type == 'uploadfile') {
    wx.uploadFile({
      url,
      header: {
        Authorization: app.globalData.accessToken ? 'Bearer ' + app.globalData.accessToken : '',
        "Content-Type": 'multipart/form-data'
      },
      filePath: data.filePath,
      name: data.filePathName,
      formData: data.data,
      timeout,
      success: function (res) {
        intercept(res, resolve, reject)
      },
      fail: function (err) {
        reject(err)
      }
    })

  } else if (apiData.type == 'downloadfile') {

    wx.downloadFile({
      url,
      header: {
        Authorization: app.globalData.accessToken ? 'Bearer ' + app.globalData.accessToken : ''
      },
      filePath: data.filePath,
      success: function (res) {
        intercept(res, resolve, reject)
      },
      fail: function (err) {
        reject(err)
      }
    })

  }
}